package com.ruoyi.zsyh.controller.applet.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 产品Controller
 */
@Controller
@RequestMapping("/applet/zsyh/shopParts")
public class ZsyhShopPartsAppletController extends BaseController
{

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhStoreOrderService zsyhStoreOrderService;

    @Autowired
    private IZsyhStoreOrderRelService zsyhStoreOrderRelService;

    @Autowired
    private IZsyhPlatformSellpartsService zsyhPlatformSellpartsService;

    @Autowired
    private IZsyhPlatformSellpartsspecialService zsyhPlatformSellpartsspecialService;


    /**
     * 获取平台商城的产品列表
     * @return
     */
    @RequestMapping("/getShopPartsList")
    @ResponseBody
    public AjaxResult getShopPartsList(String pageNum, String pageSize, String isHotPush, String isPost, String key, String partsType){

        ZsyhPlatformSellparts parts = new ZsyhPlatformSellparts();
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        if(EmptyUtils.isNotEmpty(isHotPush)){
            parts.setIsHotPush(isHotPush);
        }
        if(EmptyUtils.isNotEmpty(isPost)){
            parts.setIsPost(isPost);
        }
        parts.setPartsType(partsType);
        parts.setPartsName(key);
        parts.setParams(map);
        parts.setIsShow("1");

        List<ZsyhPlatformSellparts> list = zsyhPlatformSellpartsService.selectZsyhPlatformSellpartsList(parts);
        return AjaxResult.success("获取成功", list);
    }


    /**
     * 获取平台商城的产品详情
     * @return
     */
    @RequestMapping("/getShopPartsDetailsById")
    @ResponseBody
    public AjaxResult getShopPartsDetailsById(String partsId){
        return AjaxResult.success("获取成功", zsyhPlatformSellpartsService.selectZsyhPlatformSellpartsById(partsId));
    }

    /**
     * 提交订单  -- 平台产品
     * @return
     */
    @RepeatSubmit
    @RequestMapping("/submitShopParts")
    @ResponseBody
    @Transactional
    public AjaxResult submitShopParts(String userId, String partsJson, String orderName, String orderPhone, String orderAddress, String addressDistrict){

        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String storeId = store.getId();
        //解析产品json数据
        List<Map<String, Object>> list = JSON.parseObject(partsJson, new TypeReference<List<Map<String, Object>>>() {});
        List<ZsyhStoreOrderRel> relList = new ArrayList<>();
        //保存订单信息
        String id = IdWorker.getId();
        Date date = new Date();
        ZsyhStoreOrder order = new ZsyhStoreOrder();
        order.setId(id);
        order.setCreateTime(date);
        order.setAgentId(store.getAgentId());
        order.setStoreId(storeId);
        order.setOrderName(orderName);
        order.setOrderPhone(orderPhone);
        order.setOrderAddress(orderAddress);
        order.setOrderState("1");//状态（1待付款 2待发货 3已发货 4已收货 0已取消）
        order.setOrderType("1");

        Double orderMoney = 0.00;
        String oldIds = "";
        for(Map<String, Object> a:list){//解析预定产品，并保存
            String oldId = String.valueOf(a.get("id"));
            String attributeId = String.valueOf(a.get("attributeId"));
            String partsId = String.valueOf(a.get("partsId"));
            String count = String.valueOf(a.get("orderCount"));
            BigDecimal price = new BigDecimal(String.valueOf(a.get("orderPrice")));

            ZsyhStoreOrderRel rel = ZsyhStoreOrderRel.getInstance();
            rel.setId(IdWorker.getId());
            rel.setOrderId(order.getId());
            rel.setPartsId(partsId);
            rel.setAttributeId(attributeId);
            rel.setOrderCount(count);
            rel.setOrderPrice(price);
            rel.setCreateTime(date);
            rel.setIsPlatform("1");
            relList.add(rel);

            orderMoney += Double.valueOf(count) * price.doubleValue();

            oldIds += oldId + ",";

        }
        order.setOrderMoney(new BigDecimal(String.valueOf(orderMoney)).setScale(2, BigDecimal.ROUND_HALF_UP));

        ZsyhUserRepairstore repairstore = new ZsyhUserRepairstore();
        repairstore.setIsSend("1");
        repairstore.setStoreDistrict(addressDistrict);
        repairstore.setAppraisalState("2");
        List<ZsyhUserRepairstore> storeList = zsyhUserRepairstoreService.selectZsyhUserRepairstoreList(repairstore);
        if(storeList.size() > 0){
            order.setSendType("2");
            order.setSendStoreId(storeList.get(0).getId());
        }


        zsyhStoreOrderRelService.deleteZsyhStoreOrderRelByIds(oldIds);
        zsyhStoreOrderRelService.insertZsyhStoreOrderRelBatch(relList);

        zsyhStoreOrderService.insertZsyhStoreOrderApplet(order);

        return success("操作成功", order.getId());

    }



    /**
     * 师傅查看自己的订单列表
     * @param userId
     * @param orderState  状态（1待付款 2待发货 3已发货 4已收货 0已取消）
     * @return
     */
    @RequestMapping("/getShopPartsOrderList")
    @ResponseBody
    @Transactional
    public AjaxResult getShopPartsOrderList(String userId, String orderState, String pageNum, String pageSize){
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhStoreOrder order = new ZsyhStoreOrder();
        order.setStoreId(repairId);
        order.setOrderState(orderState);
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("orderState", "未取消");
        order.setParams(map);
        List<ZsyhStoreOrder> list = zsyhStoreOrderService.selectZsyhStoreOrderList(order);
        for(ZsyhStoreOrder storeOrder:list){
            String id = storeOrder.getId();
            ZsyhStoreOrderRel rel = new ZsyhStoreOrderRel();
            rel.setOrderId(id);
            List<ZsyhStoreOrderRel> relList = zsyhStoreOrderRelService.selectZsyhStoreOrderRelList(rel);
            storeOrder.setZsyhStoreOrderRelList(relList);
        }
        return success("成功", list);

    }


    /**
     * 订单详情
     * @return
     */
    @RequestMapping("/getShopPartsOrderDetails")
    @ResponseBody
    @Transactional
    public AjaxResult getShopPartsOrderDetails(String orderId){
        ZsyhStoreOrder order = zsyhStoreOrderService.selectZsyhStoreOrderById(orderId);
        return success("成功", order);
    }


    /**
     * 确认收货
     * @param orderId
     * @return
     */
    @RequestMapping("/deliveryShopPartsOrder")
    @ResponseBody
    @Transactional
    public AjaxResult deliveryShopPartsOrder(String orderId){
        ZsyhStoreOrder order = new ZsyhStoreOrder();
        order.setId(orderId);
        order.setOrderState("4");
        order.setDeliveryTime(new Date());
        zsyhStoreOrderService.updateZsyhStoreOrderApplet(order);
        return success("成功");
    }

    /**
     * 获取活动产品列表
     * @param specialType 分类 1普通活动 2推广活动
     * @return
     */
    @RequestMapping("/getShopPartsSpecialList")
    @ResponseBody
    @Transactional
    public AjaxResult getShopPartsSpecialList(String specialType, String pageNum, String pageSize){
        ZsyhPlatformSellpartsspecial partsspecial = new ZsyhPlatformSellpartsspecial();
        partsspecial.setAttributeName(specialType);

        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        partsspecial.setParams(map);
        List<ZsyhPlatformSellpartsspecial> list = zsyhPlatformSellpartsspecialService.selectZsyhPlatformSellpartsspecialList(partsspecial);
        return success("成功", list);
    }

    /**
     * 获取活动产品详情
     * @return
     */
    @RequestMapping("/getShopPartsSpecialById")
    @ResponseBody
    @Transactional
    public AjaxResult getShopPartsSpecialById(String id){
        return success("成功", zsyhPlatformSellpartsspecialService.selectZsyhPlatformSellpartsspecialById(id));
    }



    /**
     * 鉴定点查看订单列表
     * @param userId
     * @param orderState  状态（1待付款 2待发货 3已发货 4已收货 0已取消）
     * @return
     */
    @RequestMapping("/getShopPartsOrderListByStoreId")
    @ResponseBody
    @Transactional
    public AjaxResult getShopPartsOrderListByStoreId(String userId, String orderState, String pageNum, String pageSize){
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String storeId = store.getId();

        ZsyhStoreOrder order = new ZsyhStoreOrder();
        order.setSendStoreId(storeId);
        order.setOrderState(orderState);
        Map map = new HashedMap();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("orderState", "未取消");
        order.setParams(map);
        List<ZsyhStoreOrder> list = zsyhStoreOrderService.selectZsyhStoreOrderList(order);
        for(ZsyhStoreOrder storeOrder:list){
            String id = storeOrder.getId();
            ZsyhStoreOrderRel rel = new ZsyhStoreOrderRel();
            rel.setOrderId(id);
            List<ZsyhStoreOrderRel> relList = zsyhStoreOrderRelService.selectZsyhStoreOrderRelList(rel);
            storeOrder.setZsyhStoreOrderRelList(relList);
        }
        return success("成功", list);

    }



    /**
     * 鉴定点 发货
     * @param orderId
     * @return
     */
    @RequestMapping("/sendShopPartsOrder")
    @ResponseBody
    @Transactional
    public AjaxResult sendShopPartsOrder(String orderId, String logisticsCompany, String logisticsCompanyNum, String logisticsNum){
        ZsyhStoreOrder order = new ZsyhStoreOrder();
        order.setId(orderId);
        order.setOrderState("3");
        order.setLogisticsCompany(logisticsCompany);
        order.setLogisticsCompanyNum(logisticsCompanyNum);
        order.setLogisticsNum(logisticsNum);
        order.setDeliveryTime(new Date());
        zsyhStoreOrderService.updateZsyhStoreOrderApplet(order);
        return success("成功");
    }

}
